package com.yfunc.common.persistence.defaults;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

public class SqlSessionTemplate {

	private SqlSessionFactory sqlSessionFactory;

	public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
		this.sqlSessionFactory = sqlSessionFactory;
	}

	public <T> T call(Call<T> call) {

		if (call == null) {
			throw new IllegalArgumentException(" Call is required! ");
		}
		SqlSession session = getSession();
		try {
			return call.on(session);
		} finally {
			this.closeSession(session);
		}
	}

	private SqlSession getSession() {
		return sqlSessionFactory.openSession();
	}

	private void closeSession(SqlSession session) {
		session.close();
	}

	public interface Call<E> {
		E on(SqlSession session);
	}
}
